<template>
  <el-card>
    <el-table :data="tableData" stripe border style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-form label-position="left" inline class="expand-content">
            <el-form-item label="食品名称">
              <span>{{ scope.row.name }}</span>
            </el-form-item>
            <el-form-item label="餐馆名称">
              <span>{{ scope.row.restaurant_name }}</span>
            </el-form-item>
            <el-form-item label="食品ID">
              <span>{{ scope.row.item_id }}</span>
            </el-form-item>
            <el-form-item label="餐馆ID">
              <span>{{ scope.row.restaurant_id }}</span>
            </el-form-item>
            <el-form-item label="食品介绍">
              <span>{{ scope.row.description }}</span>
            </el-form-item>
            <el-form-item label="餐馆地址">
              <span>{{ scope.row.restaurant_address }}</span>
            </el-form-item>
            <el-form-item label="食品评分">
              <span>{{ scope.row.rating }}</span>
            </el-form-item>
            <el-form-item label="食品分类">
              <span>{{ scope.row.category_name }}</span>
            </el-form-item>
            <el-form-item label="月销量">
              <span>{{ scope.row.month_sales }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="食品名称" width="200"> </el-table-column>
      <el-table-column prop="description" label="食品介绍" width="200"> </el-table-column>
      <el-table-column prop="rating" label="评分"> </el-table-column>
      <el-table-column prop="" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" plain @click="handleFoodEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" plain @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="offset" :page-sizes="[20, 25, 30, 35, 40]" :page-size="limit" layout="total, sizes, prev, pager, next, jumper" :total="count"> </el-pagination>

    <!-- 编辑对话框 -->
    <el-dialog title="修改食品信息" :visible.sync="dialogVisibleEdit" width="50%">
      <el-form ref="form" :model="selectTable" label-width="80px">
        <el-form-item label="食品名称">
          <el-input v-model="selectTable.name"></el-input>
        </el-form-item>
        <el-form-item label="食品介绍">
          <el-input v-model="selectTable.description"></el-input>
        </el-form-item>
        <!-- 食品分类 -->
        <el-form-item label="食品分类">
          <el-select v-model="selectVal" :placeholder="selectMenu.label" @change="handleSelect">
            <el-option v-for="item in menuOptions" :key="item.value" :label="item.label" :value="item.index"> </el-option>
          </el-select>
        </el-form-item>
        <!-- 食品图片 -->
        <el-form-item label="食品图片">
          <el-upload class="avatar-uploader" :action="baseURL + '/v1/addimg/food'" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="selectTable.image_path" :src="baseImgPath + selectTable.image_path" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>

      <!--  -->
      <el-row style="overflow:auto;text-align:center">
        <el-table :data="specs" border style="margin-bottom:20px;">
          <el-table-column prop="specs_name" label="规格"></el-table-column>
          <el-table-column prop="packing_fee" label="包装费"></el-table-column>
          <el-table-column prop="price" label="价格"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="danger" size="mini" @click="deleteSpecs(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 添加 -->
        <el-button type="primary" @click="specsAddVisible = true">添加规格</el-button>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="updateFood">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加规格 -->
    <el-dialog title="添加规格" :visible.sync="specsAddVisible" width="50%">
      <!-- 表单区域 -->
      <el-form :model="specsForm" :rules="specsFormrules" ref="ruleFormRef" label-width="100px">
        <el-form-item label="规格" prop="specs_name">
          <el-input v-model.trim="specsForm.specs_name"></el-input>
        </el-form-item>
        <el-form-item label="包装费">
          <el-input-number v-model="specsForm.packing_fee" :min="0" :max="100"></el-input-number>
        </el-form-item>
        <el-form-item label="价格">
          <el-input-number v-model="specsForm.price" :min="0" :max="10000"></el-input-number>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="specsAddVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSpecsFormOK">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { baseURL, baseImgPath } from '../api/env'
import { getFoodsCount, getResturantDetail, getMenuById, updateFood, deleteFood } from '../api/index'
import request from '../api/axiosApi'
export default {
  data() {
    return {
      baseURL,
      baseImgPath,
      limit: 20,
      offset: 0,
      count: 0,
      tableData: [],
      dialogVisibleEdit: false,
      specsAddVisible: false,
      selectTable: {},
      selectMenu: {},
      menuOptions: [],
      selectVal: null,
      restaurant_id: null,
      // 添加规格表单数据
      specsForm: {
        specs_name: '',
        packing_fee: 0,
        price: 20
      },
      specsFormrules: {
        specs_name: [{ required: true, message: '请输入规格', trigger: 'blur' }]
      }
    }
  },
  created() {
    console.log(this.$route.query)
    this.restaurant_id = this.$route.query.restaurant_id
    this.initData()
  },
  computed: {
    specs() {
      const specs = []
      if (this.selectTable.specfoods) {
        this.selectTable.specfoods.forEach(item => {
          specs.push({
            specs_name: item.specs_name,
            packing_fee: item.packing_fee,
            price: item.price
          })
        })
      }
      return specs
    }
  },
  methods: {
    // 获取食品总数量
    async initData() {
      try {
        const { data: res } = await getFoodsCount()
        if (res.status === 1) {
          this.count = res.count
        } else {
          throw new Error('获取数据失败')
        }
        this.getFoodsInfo()
      } catch (error) {
        console.log(error)
      }
    },
    // 获取食品列表
    async getFoodsInfo() {
      const { data: res } = await request.get(`/shopping/v2/foods?limit=${this.limit}&offset=${this.offset}`)
      this.tableData = res
    },
    handleSizeChange(pageSize) {
      this.limit = pageSize
    },
    handleCurrentChange(pageNum) {
      this.offset = pageNum
      this.getFoodsInfo()
    },
    // 点击编辑按钮，弹出对话框
    handleFoodEdit(row) {
      this.getSelectItemData(row, 'edit')
      this.dialogVisibleEdit = true
    },
    // 获取食品信息
    async getSelectItemData(row, type) {
      console.log(row.restaurant_id)
      const { data: restaurant } = await getResturantDetail(row.restaurant_id)
      const { data: category } = await getMenuById(row.category_id)
      this.selectTable = { ...row, ...{ restaurant_name: restaurant.name, restaurant_address: restaurant.address, category_name: category.name } }
      this.selectMenu = { label: category.name, value: row.category_id }
      // this.tableData.splice(row.index)
      // if (type === 'edit' && this.restaurant_id !== row.restaurant_id) {
      if (type === 'edit') {
        this.getMenuInfo()
      }
    },
    async getMenuInfo() {
      this.menuOptions = []
      try {
        const { data: menu } = await request.get(`/shopping/v2/menu?restaurant_id= ${this.selectTable.restaurant_id}&allMenu=true`)
        // console.log(res)
        menu.forEach((item, index) => {
          this.menuOptions.push({
            label: item.name,
            value: item.id,
            index
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    // success
    handleAvatarSuccess(res, file) {
      if (res.status === 1) {
        this.selectTable.image_path = res.image_path
      } else {
        this.$message.error('上传图片失败')
      }
    },
    beforeAvatarUpload(file) {
      const isRightType = file.type === 'image/jpeg' || file.type === 'image/png'
      const isSize2M = file.size / 1024 / 1024 < 2
      if (!isRightType) {
        this.$message.error('上传头像图片只能是JPG格式!')
      }
      if (!isSize2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
    },
    // 提交添加规格
    addSpecsFormOK() {
      this.$refs.ruleFormRef.validate(valid => {
        if (!valid) return this.$message.error('请输入规格')
        this.specs.push({ ...this.specsForm })
        this.specsForm.specs_name = ''
        this.specsForm.packing_fee = 0
        this.specsForm.price = 20
        this.specsAddVisible = false
      })
    },
    async updateFood() {
      this.dialogVisibleEdit = false
      try {
        const postData = { ...this.selectTable, ...{ new_category_id: this.selectMenu.value, specs: this.specs } }
        const { data: res } = await updateFood(postData)
        if (res.status === 1) {
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.log(error)
      }
    },
    handleSelect(index) {
      this.selectMenu = this.menuOptions[index]
    },
    // 删除specs
    deleteSpecs(index) {
      this.specs.splice(index, 1)
    },
    // 删除
    async handleDelete(index, row) {
      try {
        const { data: res } = await deleteFood(row.item_id)
        if (res.status === 1) {
          this.$message.success('删除食品成功')
          this.tableData.splice(index, 1)
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.expand-content {
  padding: 20px 40px;
  display: flex;
  flex-wrap: wrap;
  /deep/.el-form-item {
    width: 50%;
    margin: 0;
    .el-form-item__label {
      margin-right: 70px;
      color: #99a9bf;
    }
  }
}
.avatar-uploader {
  width: 140px;
  height: 140px;
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
